<?php
$pageTitle = "首页";
$currentPage = "index";
include('../resource/db/db.php');
include('../resource/navbar.php');
if (!isset($_COOKIE['user_id'])) {
    header("Location: ../main/login.php");
    exit();
}
$user_id = $_COOKIE['user_id'];


// 获取所有is_deleted=1的卡片，将所有study_records中对应的记录的is_deleted设置为1
$deleted_cards_sql = "SELECT set_id, card_id FROM cards WHERE is_deleted=TRUE";
$deleted_cards_result = $conn->query($deleted_cards_sql);
if ($deleted_cards_result->num_rows > 0) {
    while ($row = $deleted_cards_result->fetch_assoc()) {
        $card_id = $row['card_id'];
        $update_study_records_sql = "UPDATE study_records SET is_deleted=TRUE WHERE card_id='$card_id AND user_id='$user_id AND set_id='{$row['set_id']}'";
        $conn->query($update_study_records_sql);
    }
}
// 将所有无法对应到cards表中的study_records记录的is_deleted设置为1
$deleted_records_sql = "SELECT record_id FROM study_records WHERE user_id='$user_id' AND card_id NOT IN (SELECT card_id FROM cards WHERE is_deleted=FALSE)";
$deleted_records_result = $conn->query($deleted_records_sql);
if ($deleted_records_result->num_rows > 0) {
    while ($row = $deleted_records_result->fetch_assoc()) {
        $record_id = $row['record_id'];
        $update_study_records_sql = "UPDATE study_records SET is_deleted=TRUE WHERE record_id='$record_id'";
        $conn->query($update_study_records_sql);
    }
}

// 获取用户的学习盒子信息
$box_sql = "SELECT box_number, card_id, COUNT(*) as card_count
            FROM study_records 
            WHERE user_id='$user_id' AND is_deleted=FALSE
            GROUP BY box_number";
$box_result = $conn->query($box_sql);


// 获取卡组和卡片数量（set_id, card_id）信息
$sql = "SELECT sets.set_id, sets.name, COUNT(cards.card_id) as card_count
        FROM sets 
        LEFT JOIN cards ON sets.set_id = cards.set_id AND cards.is_deleted=FALSE
        WHERE sets.user_id='$user_id' AND sets.is_deleted=FALSE
        GROUP BY sets.set_id, sets.name";
$result = $conn->query($sql);

$boxes = [
    1 => ['title' => '今天', 'count' => 0],
    2 => ['title' => '明天', 'count' => 0],
    3 => ['title' => '一周后', 'count' => 0],
    4 => ['title' => '十四天后', 'count' => 0],
    5 => ['title' => '一个月后', 'count' => 0],
    6 => ['title' => '永恒', 'count' => 0],
];

if ($box_result->num_rows > 0) {
    while ($row = $box_result->fetch_assoc()) {
        $boxNumber = $row['box_number'];
        if (isset($boxes[$boxNumber])) {
            $boxes[$boxNumber]['count'] = $row['card_count'];
        }
    }
}
?>

<!DOCTYPE html>
<html>

<head>
    <title>首页</title>
    <link rel="stylesheet" href="../resource/css/styles.css">
    <style>
        .search-container .form-group input[type="text"] {
            margin-right: 10px;
        }

        .form-group {
            margin-bottom: 1rem;
            display: flex;
        }

        .set-container {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 20px;
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .set-link {
            text-decoration: none;
            color: black;
        }

        .set {
            width: 150px;
            height: 150px;
            background-color: #f0f0f0;
            margin-right: 20px;
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 18px;
            text-align: center;
            padding: 10px;
        }

        .box-container {
            display: flex;
            flex-wrap: wrap;
            margin-bottom: 20px;
            margin-top: 20px;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .box {
            width: calc(33.33% - 20px);
            height: 100px;
            background-color: #f0f0f0;
            margin-right: 20px;
            margin-bottom: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
            font-size: 24px;
            text-align: center;
            padding: 10px;
        }

        .box:nth-child(3n) {
            margin-right: 0;
        }
    </style>
</head>

<body>
    <div class="container">
        <!-- 搜索框 -->
        <div class="search-container">
            <h2>搜索</h2>
            <form method="post" action="search.php">
                <div class="form-group">
                    <input type="text" id="search_term" name="search_term" class="form-control" required>
                    <button type="submit" class="btn btn-primary">🔍</button>
                </div>
            </form>
        </div>

        <h2>您的卡组</h2>
        <div class="set-container">
            <?php
            if ($result->num_rows > 0) {
                while ($row = $result->fetch_assoc()) {
                    echo "<a href='../learn/set.php?set_id=" . $row['set_id'] . "' class='set-link'>";
                    echo "<div class='set'>" . htmlspecialchars($row['name']) . "<br>" . htmlspecialchars($row['card_count']) . " 张卡片</div>";
                    echo "</a>";
                }
            } else {
                echo "<p>您暂时没有卡组。</p>";
            }
            ?>
        </div>

        <h2>您的学习盒子</h2>
        <div class="box-container">
            <?php
            foreach ($boxes as $box) {
                echo "<div class='box'>" . $box['title'] . "<br>" . $box['count'] . " 张卡片</div>";
            }
            ?>
        </div>
        <script>
            // 点击盒子进入对应的review页面
            document.querySelectorAll('.box').forEach(function(box) {
                box.addEventListener('click', function() {
                    var boxTitle = box.innerText.split('\n')[0];
                    var boxNumber = 1;
                    switch (boxTitle) {
                        case '今天':
                            boxNumber = 1;
                            break;
                        case '明天':
                            boxNumber = 2;
                            break;
                        case '一周后':
                            boxNumber = 3;
                            break;
                        case '十四天后':
                            boxNumber = 4;
                            break;
                        case '一个月后':
                            boxNumber = 5;
                            break;
                        case '永恒':
                            boxNumber = 6;
                            break;
                    }
                    // console.log(boxNumber);
                    // 获取对应box最小record_id的值
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', './get-min-record-id.php?box_number=' + boxNumber, true);
                    xhr.onreadystatechange = function() {
                        if (xhr.readyState === 4 && xhr.status === 200) {
                            var record_id = xhr.responseText;
                            // console.log(record_id);
                            window.location.href = '../learn/review.php?box_number=' + boxNumber + '&record_id=' + record_id;
                        }
                    };
                    xhr.send();
                });
            });
        </script>
    </div>
</body>

</html>